package com.base.common.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.webkit.WebView;

import androidx.multidex.MultiDex;

import com.base.common.R;
import com.base.common.utils.IOUtils;
import com.base.common.utils.LogUtil;
import com.base.common.utils.SystemUtils;
import com.base.common.utils.UIUtils;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.upgrade.UpgradeStateListener;


public class BaseApp extends Application {

    public static final String TAG = "BaseApp";

    // 获取到主线程的上下文
    private static Application mContext = null;
    // 获取到主线程的handler
    private static Handler mMainThreadHandler = null;
    // 获取到主线程的looper
    private static Looper mMainThreadLooper = null;
    // 获取到主线程
    private static Thread mMainThead = null;
    // 获取到主线程的id
    private static int mMainTheadId;


    @Override
    public void onCreate() {
        super.onCreate();


        //线程池工具类初始化
        mContext = this;
        mMainThreadHandler = new Handler();
        mMainThreadLooper = getMainLooper();
        mMainThead = Thread.currentThread();
        // android.os.Process.myUid()获取到用户id
        // android.os.Process.myPid();//获取到进程id
        // android.os.Process.myTid()获取到调用线程的id
        mMainTheadId = Process.myTid();// 主线程id

        registerActivityListener();

        IOUtils.initRootDirectory();

        //自动检查更新开关
        Beta.autoCheckUpgrade = false;
        // 设置升级检查周期为60s(默认检查周期为0s)，60s内SDK不重复向后台请求策略);
        Beta.upgradeCheckPeriod = 60 * 1000;
        //设置sd卡的Download为更新资源存储目录
//        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        //设置Wifi下自动下载
        Beta.autoDownloadOnWifi = true;
        // 设置是否提示用户重启
        Beta.canNotifyUserRestart = false;

        /**
         *  设置自定义升级对话框UI布局
         *  注意：因为要保持接口统一，需要用户在指定控件按照以下方式设置tag，否则会影响您的正常使用：
         *  标题：beta_title，如：android:tag="beta_title"
         *  升级信息：beta_upgrade_info  如： android:tag="beta_upgrade_info"
         *  更新属性：beta_upgrade_feature 如： android:tag="beta_upgrade_feature"
         *  取消按钮：beta_cancel_button 如：android:tag="beta_cancel_button"
         *  确定按钮：beta_confirm_button 如：android:tag="beta_confirm_button"
         *  详见layout/upgrade_dialog_fragment.xml
         */
        Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog_fragment;


        /* 设置更新状态回调接口 */
        Beta.upgradeStateListener = new UpgradeStateListener() {
            @Override
            public void onUpgradeSuccess(boolean isManual) {
                LogUtil.d(TAG, "更新成功");
//                if (isManual) UIUtils.showToastSafes("请更新最新版本");
            }

            /**
             * 更新失败
             * @param isManual  true:手动检查 false:自动检查
             */
            @Override
            public void onUpgradeFailed(boolean isManual) {
                LogUtil.d(TAG, "升级失败");
            }

            /**
             * 正在更新
             * @param isManual
             */
            @Override
            public void onUpgrading(boolean isManual) {

                LogUtil.d(TAG, "正在更新...");
            }

            @Override
            public void onDownloadCompleted(boolean b) {
                LogUtil.d(TAG, "下载完成");
            }

            /**
             * 没有更新
             * @param isManual
             */
            @Override
            public void onUpgradeNoVersion(boolean isManual) {
                LogUtil.d(TAG, "没有更新");
//                if (PublicStaticValue.isCheckUpdate = true) {
//                    PublicStaticValue.isCheckUpdate = false;
//                    UIUtils.showToastSafes("已是最新版本");
//                }
                if (!isManual) {
//                    UIUtils.showToastSafes("已是最新版本");
                }
            }
        };

         //异常日志:Caused by: java.lang.RuntimeException: Using WebView from more than one process at once with the same data directory is not supported. https://crbug.com/558377
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(this);
            if (UIUtils.getPackageName().equals(processName)) {//判断不等于默认进程名称
                WebView.setDataDirectorySuffix(processName);
            }
        }
    }

    public String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

    }


    public void registerActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                LogUtil.d("JPush BaseApp" + activity.getClass().getSimpleName());
                AppManager.getInstance().addActivity(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                AppManager.getInstance().removeActivity(activity);
            }
        });
    }

    public static Application getApplication() {
        return mContext;
    }

    public static Handler getMainThreadHandler() {
        return mMainThreadHandler;
    }

    public static Looper getMainThreadLooper() {
        return mMainThreadLooper;
    }

    public static Thread getMainThread() {
        return mMainThead;
    }

    public static int getMainThreadId() {
        return mMainTheadId;
    }

}
